package com.hnu.store.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CutText {

  public static int readFile(String filePath) throws FileNotFoundException {
    int count = 0;
    File file = new File(filePath);
    FileInputStream fis = new FileInputStream(file);
    Scanner scanner = new Scanner(fis);
    while (scanner.hasNextLine()) {
      scanner.nextLine();
      count++;
    }
    return count;
  }

  /**
   * 切割文本
   * @param filePath 源文件路径
   * @param path 新生成文件的路径
   * @param start 起始行数
   * @param end 结束行数
   */
  public static void cut(String filePath, String path, int start, int end) {
    FileReader fileReader;
    try {
      fileReader = new FileReader(filePath);
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      int rowNum = 1;
      String row;

      FileWriter fileWriter = new FileWriter(path);

      while ((row = bufferedReader.readLine()) != null) {
        //  目标行数内
        if(rowNum>=start&&rowNum<=end) {
          fileWriter.append(row).append("\r\n");
        } else if (rowNum>end) {
          break;
        }
        rowNum++;
      }
      fileWriter.close();
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }

  }

}
